package org.pombo.sqm;

import org.pombo.gtm.Action;
import org.pombo.gtm.Strategy;
import org.pombo.gtm.StrategyNode;

class PlayerNodeProbabilityCalculator implements NodeProbabilityCalculator<StrategyNode> {

	private StrategyNode node;
	private Strategy strategy;
	private ProbabilityCalculatorFactory calculate;

	PlayerNodeProbabilityCalculator(
			ProbabilityCalculatorFactory probabilityCalculatorFactory,
			Strategy strategy) {
		this.strategy = strategy;
		this.calculate = probabilityCalculatorFactory;
	}

	public void setNode(StrategyNode node) {
		this.node = node;
	}

	public NodeProbabilities nodeProbabilities(double baseProbability) {
		NodeProbabilities nodeProbabilities = new NodeProbabilities();
		nodeProbabilities.add(this.node, baseProbability);
		nodeProbabilities = this.addSubNodesToProbabilitiesMap(nodeProbabilities, baseProbability);
		return nodeProbabilities;
	}

	private NodeProbabilities addSubNodesToProbabilitiesMap(
			NodeProbabilities nodeProbabilities,
			double baseProbability) {
		for (Action action : this.node.getActions()) {
			double branchProbability = this.strategy.getProbabilityForAction(action) * baseProbability;
			NodeProbabilities branchProbabilities = this.calculate.on(this.node.getNodeForAction(action)).nodeProbabilities(branchProbability);
			nodeProbabilities.add(branchProbabilities);
		}
		return nodeProbabilities;
	}
}
